<?php

namespace app\model;

use think\Model;

class Order extends Model
{
    protected $name = 'orders';
    
    // 设置字段信息
    protected $schema = [
        'id' => 'int',
        'order_no' => 'string',
        'platform' => 'string',
        'shop_id' => 'string',
        'shop_name' => 'string',
        'order_date' => 'date',
        'customer_name' => 'string',
        'buyer_account' => 'string',
        'buyer_user_type' => 'int',
        'product_name' => 'string',
        'quantity' => 'int',
        'unit_price' => 'decimal',
        'total_amount' => 'decimal',
        'order_status' => 'int',
        'order_status_str' => 'string',
        'pay_amount' => 'decimal',
        'promotion_amount' => 'decimal',
        'post_amount' => 'decimal',
        'cost_price' => 'decimal',
        'profit' => 'decimal',
        'status' => 'string',
        'pay_time' => 'datetime',
        'ship_time' => 'datetime',
        'confirm_receipt_time' => 'datetime',
        'seller_words' => 'text',
        'buyer_words' => 'text',
        'tracking_number' => 'string',
        'logistics_name' => 'string',
        'logistics_code' => 'string',
        'receiver_name' => 'string',
        'receiver_phone' => 'string',
        'receiver_address' => 'text',
        'province' => 'string',
        'city' => 'string',
        'district' => 'string',
        'street' => 'string',
        'after_sale_status' => 'int',
        'after_sale_type' => 'int',
        'after_sale_reason' => 'string',
        'refund_amount' => 'decimal',
        'goods_id' => 'string',
        'sku_id' => 'string',
        'goods_spec' => 'text',
        'goods_img' => 'string',
        'mall_id' => 'string',
        'parent_order_id' => 'string',
        'channel_payment_no' => 'string',
        'pay_type' => 'string',
        'platform_cost_amount' => 'decimal',
        'commission_price' => 'decimal',
        'is_auto' => 'int',
        'is_encrypt_order' => 'int',
        'source_data' => 'text',
        'sync_date' => 'datetime',
        'sync_record_id' => 'int',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 类型转换
    protected $type = [
        'quantity' => 'integer',
        'unit_price' => 'float',
        'total_amount' => 'float',
        'cost_price' => 'float',
        'profit' => 'float',
        'order_date' => 'date',
        'sync_date' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'pay_amount' => 'float',
        'promotion_amount' => 'float',
        'post_amount' => 'float',
        'refund_amount' => 'float',
        'platform_cost_amount' => 'float',
        'commission_price' => 'float',
        'order_status' => 'integer',
        'after_sale_status' => 'integer',
        'after_sale_type' => 'integer',
        'buyer_user_type' => 'integer',
        'is_auto' => 'integer',
        'is_encrypt_order' => 'integer',
        'sync_record_id' => 'integer',
        'pay_time' => 'datetime',
        'ship_time' => 'datetime',
        'confirm_receipt_time' => 'datetime'
    ];

    /**
     * 获取订单列表
     * @param array $params 查询参数
     * @return array
     */
    public static function getOrderList($params = [])
    {
        $query = self::order('order_date', 'desc');

        // 平台筛选
        if (!empty($params['platform'])) {
            $query->where('platform', $params['platform']);
        }

        // 订单状态筛选
        if (!empty($params['order_status'])) {
            $query->where('order_status_str', 'like', '%' . $params['order_status'] . '%');
        }

        // 店铺名称筛选
        if (!empty($params['shop_name'])) {
            $query->where('shop_name', 'like', '%' . $params['shop_name'] . '%');
        }

        // 日期范围筛选
        if (!empty($params['start_date'])) {
            $query->where('order_date', '>=', $params['start_date']);
        }
        if (!empty($params['end_date'])) {
            $query->where('order_date', '<=', $params['end_date']);
        }

        // 关键词搜索
        if (!empty($params['keyword'])) {
            $query->where(function ($q) use ($params) {
                $q->where('order_no', 'like', '%' . $params['keyword'] . '%')
                  ->whereOr('customer_name', 'like', '%' . $params['keyword'] . '%')
                  ->whereOr('product_name', 'like', '%' . $params['keyword'] . '%')
                  ->whereOr('goods_id', 'like', '%' . $params['keyword'] . '%')
                  ->whereOr('parent_order_id', 'like', '%' . $params['keyword'] . '%');
            });
        }

        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        return [
            'total' => $total,
            'list' => $list,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取订单统计
     * @return array
     */
    public static function getOrderStats()
    {
        // 总订单数
        $totalOrders = self::count();
        
        // 今日订单数
        $todayOrders = self::where('order_date', '>=', date('Y-m-d'))->count();
        
        // 本周订单数
        $weekOrders = self::where('order_date', '>=', date('Y-m-d', strtotime('-7 days')))->count();
        
        // 本月订单数
        $monthOrders = self::where('order_date', '>=', date('Y-m-01'))->count();
        
        // 总金额
        $totalAmount = self::sum('total_amount');
        
        // 总利润
        $totalProfit = self::sum('profit');
        
        // 平台统计
        $platformStats = self::field('platform, count(*) as count, sum(total_amount) as amount, sum(profit) as profit')
            ->group('platform')
            ->select()
            ->toArray();

        return [
            'total_orders' => $totalOrders,
            'today_orders' => $todayOrders,
            'week_orders' => $weekOrders,
            'month_orders' => $monthOrders,
            'total_amount' => $totalAmount,
            'total_profit' => $totalProfit,
            'platform_stats' => $platformStats
        ];
    }

    /**
     * 获取平台列表
     * @return array
     */
    public static function getPlatforms()
    {
        return self::field('platform')
            ->group('platform')
            ->column('platform');
    }

    /**
     * 获取状态列表
     * @return array
     */
    public static function getStatuses()
    {
        return self::field('status')
            ->group('status')
            ->column('status');
    }
} 